<template>
  <div>
    <a-table
      :columns="tableColumns"
      :data-source="data"
      :style="{ width: '100%' }"
      :pagination="false"
      :custom-row="r => ({ onClick: () => emits('rowClick', r) })"
      v-bind="$attrs"
    >
      <template #expandIcon="scoped">
        <slot name="expandIcon" v-bind="scoped"></slot>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-for="col in columns.filter(c => c.dataIndex === column.dataIndex)" :key="col.dataIndex">
          <template v-if="col.slot">
            <slot :name="col.slot" v-bind="{ column, record }"> </slot>
          </template>
          <template v-else>
            {{ replaceEmptyStr(record[column.dataIndex as string]) }}
          </template>
        </template>

        <template v-if="column.dataIndex === 'action'">
          <div class="flex gap-12" @click.stop>
            <a-button
              v-for="btn in tableActionOption.list.filter(it => !it.hide || !it.hide(record))"
              :key="btn.text || btn.dynamicText(record)"
              :disabled="btn.disabled && btn.disabled(record)"
              type="link"
              @click="btn.onClick(record)"
              >{{ btn.text || btn.dynamicText(record) }}</a-button
            >
            <a-dropdown v-if="tableActionOption.more.filter(it => !it.hide || !it.hide(record)).length">
              <!-- <a-button type="link">更多</a-button> -->
              <a-button type="text" class="icon-only-btn" @click.stop>
                <i class="iconfont icon-more-line"></i>
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item
                    v-for="btn in tableActionOption.more.filter(it => !it.hide || !it.hide(record))"
                    :key="btn.text || btn.dynamicText(record)"
                    @click="btn.onClick(record)"
                  >
                    <a href="javascript:;">{{ btn.text || btn.dynamicText(record) }}</a>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>
        </template>
      </template>
    </a-table>
    <g-pagination
      :offset="pageForm.offset"
      :limit="pageForm.limit"
      :total="pageForm.total"
      @update:offset="updateOffset"
      @update:limit="updateLimit"
      @change="emits('getDataList')"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ColumnType } from 'ant-design-vue/es/table'
  import { ref } from 'vue'

  import { checkKey } from '@/directives/auth'
  import { filterTableColumns, MyColumnType, replaceEmptyStr } from '@/utils'

  interface PageForm {
    offset: number
    limit: number
    total: number
    [key: string]: any
  }

  interface ActionBtn {
    /** 按钮名称  */
    text?: string
    /** 按钮对应的权限字段 */
    auth?: string | string[]
    /** 是否隐藏 */
    hide?: (record: any) => boolean
    /** 是否禁用 */
    disabled?: (record: any) => boolean
    /** 按钮名称（动态）  */
    dynamicText?: (record: any) => string
    onClick: (...args: any[]) => void
  }

  interface ActionOption {
    // 平铺的
    list?: ActionBtn[]
    // 更多
    more?: ActionBtn[]
  }

  interface Props {
    /** 表头项 */
    columns: MyColumnType[]
    /** 数据 */
    data: Record<string, any>[]

    /** 操作栏宽度 */
    actionWidth?: number

    /** 操作按钮列表 */
    actionOption?: ActionOption
  }

  const pageForm = defineModel<PageForm>('pageForm', { required: true })

  const props = withDefaults(defineProps<Props>(), {
    actionWidth: 120,
    actionOption: () => ({
      list: [],
      more: []
    })
  })

  const emits = defineEmits<{
    (e: 'rowClick', params: any): void
    (e: 'getDataList'): void
  }>()

  // 表格列
  const tableColumns = ref<ColumnType[]>()
  // 表格操作项
  const tableActionOption = {} as ActionOption

  const initColumns = () => {
    tableColumns.value = filterTableColumns(props.columns)
    // 根据操作按钮个数，判断是否显示操作栏
    if (tableActionOption.list?.length || tableActionOption.more?.length) {
      tableColumns.value.push({
        title: '',
        dataIndex: 'action',
        width: props.actionWidth
      })
    }
  }

  const initActionOption = () => {
    // 过滤掉无权限按钮
    Object.assign(tableActionOption, {
      list: props.actionOption?.list?.filter(it => checkKey(it.auth || '')) || [],
      more: props.actionOption?.more?.filter(it => checkKey(it.auth || '')) || []
    })

    // 完善默认值
    tableActionOption.list = tableActionOption.list!.map(it =>
      Object.assign(
        {
          dynamicText: () => 'null'
        },
        it
      )
    )
    tableActionOption.more = tableActionOption.more!.map(it =>
      Object.assign(
        {
          dynamicText: () => 'null'
        },
        it
      )
    )
  }

  const updateOffset = (offset: number) => {
    Object.assign(pageForm.value, {
      offset
    })
  }
  const updateLimit = (limit: number) => {
    Object.assign(pageForm.value, {
      limit
    })
  }

  initActionOption()
  initColumns()
</script>
